<template>
  <div ref="treeManage" 
  :class="{'innerPageTable-box-OneTwo TreeManage-page': !useTableSearchBar}"
  class="tree-manage innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <Form
        :model="searchForm"
        ref="searchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 树编码 -->
          <Form-item prop="treeCode" :label="$t('module.treeManage.treeCode')">
            <Input
              type="text"
              :maxlength="50"
              v-model.trim="searchForm.treeCode"
              :placeholder="$t('module.treeManage.warning.enterTreeCode')"
              @on-enter="search"
            ></Input>
          </Form-item>

          <!-- 树名称 -->
          <Form-item prop="treeName" :label="$t('module.treeManage.treeName')">
            <Input
              type="text"
              :maxlength="50"
              v-model.trim="searchForm.treeName"
              :placeholder="$t('module.treeManage.warning.enterTreeName')"
              @on-enter="search"
            ></Input>
          </Form-item>
          <Form-item prop="status" :label="$t('common.status')">
            <Select
              v-model="searchForm.enabled"
              style="width:100%"
              :placeholder="$t('common.warning.selectStatus')"
              clearable
            >
              <Option v-for="item in satusList" :value="item.vsiKey" :key="item.vsiKey">{{ item.vsiValue }}</Option>
            </Select>
          </Form-item>
          <!-- 查询\重置按钮 -->
          <Form-item prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="reset" />
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="treeTable" :config="pageTableConfig">
      <!-- handler bar 查询/重置-->
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="reset" />
      </div>
      -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="add" />
        <RPButton optType="batch" @click="doDelete" />
      </div>
      <Form
        :model="searchForm"
        v-if="useTableSearchBar"
        ref="searchForm"
        slot="table-search-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 树编码 -->
          <Form-item prop="treeCode">
            <Input
              type="text"
              :maxlength="50"
              v-model.trim="searchForm.treeCode"
              :placeholder="$t('module.treeManage.warning.enterTreeCode')"
              clearable
              @on-enter="search"
              @on-blur="search"
              @on-clear="search"
            ></Input>
          </Form-item>

          <!-- 树名称 -->
          <Form-item prop="treeName">
            <Input
              type="text"
              :maxlength="50"
              v-model.trim="searchForm.treeName"
              :placeholder="$t('module.treeManage.warning.enterTreeName')"
              clearable
              @on-enter="search"
              @on-blur="search"
              @on-clear="search"
            ></Input>
          </Form-item>
          <Form-item prop="status">
            <Select
              v-model="searchForm.enabled"
              style="width:140px"
              :placeholder="$t('common.warning.selectStatus')"
              @on-change="search(1)"
              clearable
            >
              <Option v-for="item in satusList" :value="item.vsiKey" :key="item.vsiKey">{{ item.vsiValue }}</Option>
            </Select>
          </Form-item>
        </template>
      </Form>
    </InnerPageTable>
  </div>
</template>
<script>
import TreeEdit from './TreeEdit.vue'
import TreeNodeManage from './TreeNodeManage.vue'
import tenantAPI from '@/api/tenantApi.js'
import valueSetAPI from '@/api/valueSetAPI.js'
import { CoreModuleName } from '@/const.js'
import locales from './locales.js'

export default {
  mixins: [locales],
  components: {},
  props: {},
  name: 'tree-manage',
  data() {
    return {
      treeTypeList: {},
      satusList: [],
      // productList: {},
      // tenantList: {},
      tenantCode: '',
      searchForm: {
        // productCode: "",
        tenantCode: '',
        treeName: '',
        treeCode: '',
        enabled: 'ALL'
      },
      pageTableConfig: {
        action: null,
        resource: null, //default
        customDataProcess: null, //default
        loadDataFn: this.loadData,
        columnsFn: this.generateColumns,
        autoFirst: false //default false
      }
    }
  },
  computed: {},
  created: function() {
    this.init()
  },
  beforeMount: function() {},
  mounted: function() {
    this.search(1)
  },
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    init() {
      this.initTreeType()
      this.initSatus()
      // this.initProduct();
      // this.initTenant();

      // 根据当前岗位查询数据
      let { userInfo } = $store.state[CoreModuleName]
      this.tenantCode = userInfo.tenantCode
      this.searchForm.tenantCode = userInfo.tenantCode
    },
    initTreeType() {
      valueSetAPI.getValueSetByCode('treeType').then(data => {
        for (const treeType of data) {
          this.treeTypeList[treeType.vsiKey] = treeType.vsiValue
        }
      })
    },
    initSatus() {
      this.satusList = []
      valueSetAPI.getValueSetByCode('ENABLED_CODE').then(data => {
        this.satusList = data
        this.satusList.map((item, index) => {
          if (item.vsiKey == 'ALL') {
            this.satusList.splice(index, 1)
          }
        })
      })
    },
    // 初始化所属产品
    // initProduct() {
    //   valueSetAPI.getValueSetByCode("RC_PRODUCT").then(data => {
    //     for (const product of data) {
    //       this.productList[product.vsiKey] = product.vsiValue;
    //     }
    //   });
    // },
    // 初始化所属租户
    // initTenant() {
    //   tenantAPI.queryAllTenantList().then(data => {
    //     for (const tenant of data) {
    //       this.tenantList[tenant.tenantCode] = tenant.tenantName;
    //     }
    //   });
    // },
    search(page = 1) {
      let params = Object.assign({}, this.searchForm)
      if (this.searchForm.enabled == 'ALL') {
        params.enabled = null
      }
      this.$refs['treeTable'].load(params, page)
      // console.log(this.$refs.treeTable)
    },
    reset() {
      this.$refs['searchForm'].resetFields()
      this.searchForm.enabled = 'ALL'
      this.search(1)
    },
    add() {
      new this.$pageModal(
        TreeEdit,
        {
          props: {
            tenantCode: this.tenantCode
          }
        },
        data => {
          if (data) {
            this.search()
          }
        }
      )
    },
    loadData({ responseProcess, param }) {
      return window.$http.post(`${window.RPConfig.mgt}/tree/list/page`, param).then(({ data }) => {
        data.records.forEach(tree => {
          if (tree.enabled == 1) {
            tree._disabled = true
          }
        })
        responseProcess(data)
      })
    },
    generateColumns() {
      const COLUMN_WIDTH = window.RPConfig.COLUMN_WIDTH
      return [
        {
          type: 'selection',
          width: 50,
          align: 'center'
        },
        {
          title: this.$t('module.treeManage.treeCode'),
          key: 'treeCode',
          align: 'left',
          sortable: true,
          width: 180
        },
        {
          title: this.$t('module.treeManage.treeName'),
          key: 'treeName',
          align: 'left',
          sortable: true,
          width: 180
        },
        {
          title: this.$t('module.treeManage.treeType'),
          key: 'treeType',
          align: 'center',
          width: 150,
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: this.treeTypeList[params.row.treeType]
                }
              },
              this.treeTypeList[params.row.treeType] ? this.treeTypeList[params.row.treeType] : params.row.treeType
            )
          }
        },
        {
          title: this.$t('module.treeManage.description'),
          key: 'treeDesc',
          align: 'left',
          minWidth: 180
        },
        {
          title: this.$t('common.status'),
          key: 'enabled',
          align: "center",
          minWidth: 80,
          maxWidth: 80 + COLUMN_WIDTH.MAX_WIDTH_MORE,

          render: (h, params) => {
            return h(
              'StatusButton',
              {
                // 修改StatusButton内容居中
                style: {
                  "justify-content": "center"
                },

                props: {
                  status: params.row.enabled == 1 ? '0' : '1'
                }
              },
              params.row.enabled == 1 ? this.$t('common.enable') : this.$t('common.disable')
            )
          }
        },
        {
          title: this.$t('common.operating'),
          align: 'left',
          fixed: 'right',
          width: 100,
          render: (h, params) => {
            let operation = [
              {
                type: 'icon',
                icon: 'md-create',
                text: this.$t('common.edit'),
                handle: () => {
                  new this.$pageModal(
                    TreeEdit,
                    {
                      props: {
                        treeId: params.row.id,
                        tenantCode: this.tenantCode
                      }
                    },
                    data => {
                      if (data) {
                        this.search(this.$refs.treeTable.param.pageNum)
                      }
                    }
                  )
                }
              }
            ]
            if (params.row.enabled == 0) {
              operation.push({
                type: 'icon',
                icon: 'md-trash',
                text: this.$t('common.delete'),
                handle: () => {
                  this.$confirm
                    .warning(this.$t('common.warning.confirmToDelete'))
                    .then(() => {
                      window.$http.post(`${window.RPConfig.mgt}/tree/delete`, [params.row.id]).then(response => {
                        this.$message.success({
                          content: this.$t('common.deleteSuccess'),
                          duration: 3
                        })
                        this.search()
                      })
                    })
                    .catch(_ => _)
                }
              })
            }
            operation.push({
              type: 'icon',
              icon: 'md-git-merge',
              text: '维护树节点',
              handle: () => {
                new this.$sidelipPage(
                  TreeNodeManage,
                  {
                    props: {
                      treeObj: params.row
                    }
                  },
                  data => {
                    if (data) {
                      // window.alert("刷新列表");
                    }
                  }
                )
              }
            })
            return h('RowTools', {
              props: {
                data: operation
              }
            })
          }
        }
      ]
    },
    doDelete() {
      let selectedIds = this.getSelectedIds()
      if (selectedIds.length == 0) {
        this.$message.error({
          content: `${this.$t('module.treeManage.warning.selectTree')}`,
          duration: 1.5
        })
        return
      }
      this.$confirm.warning(this.$t('common.warning.confirmToDelete')).then(() => {
        window.$http.post(`${window.RPConfig.mgt}/tree/delete`, selectedIds).then(response => {
          this.$message.success({
            content: this.$t('common.deleteSuccess'),
            duration: 3
          })
          this.search()
        })
      })
    },
    getSelectedIds() {
      let list = this.$refs['treeTable'].getSelectioned() || []
      let ids = []
      for (let u of list) {
        ids.push(u.id)
      }
      return ids
    }
  },
  watch: {},
  directives: {}
}
</script>
<style lang="less">
.tree-manage {
  height: 100%;
}

.ivu-form.form-create .ivu-form-item {
  min-height: 50px;
  margin-bottom: 0;
}
// ok注释的样式
.TreeManage-page {
  .ivu-form-item {
    .ivu-form-item-content {
      width: calc(~'100% - 56px') !important;
    }
  }
}
</style>
